#include "demo.h"
#include "general_timer.h"
#include "usb_lib.h"
#include "hw_config.h"
#include "usb_pwr.h"
#include "hal_pin/hal_pin.h"
#include "general_task.h"
#include <string.h>
#include "ff.h"

FIL file;
FATFS fs;

void init_usb_module()
{
    Set_System();
    Set_USBClock();
    USB_Interrupts_Config();
    USB_Init();
    while(bDeviceState != CONFIGURED)
    {
    }
    
    USB_Configured_LED();
}

void app_demo_usb(void *p_arg)
{
    init_usb_module();
    
    while(1)
    {
        printf("run demo task\r\n");
        sleep(10);
    }
}

void app_demo_task(void *p_arg)
{
    int8_t os_err;
    FRESULT res;
    uint8_t buf[50], len;
 
    os_err = create_task(app_demo_usb, "Fatfs Task");
    if(os_err != 0)
        printf("create fatfs task fail!\r\n");

#if 1
#if 0
    
    res = f_mount(&fs, "", 1);
    while(res != FR_OK)
    {
        printf("f_mount error!\r\n");
        res = f_mount(&fs, "", 1);
        sleep(10);
    }
#endif

#if 0    
    res = f_open(&file, "hello.txt", 
                 FA_CREATE_ALWAYS | FA_WRITE);
    while(res != FR_OK)
    {
        printf("f_open error!\r\n");
        res = f_open(&file, "hello.txt", FA_CREATE_ALWAYS | FA_WRITE);
        sleep(10);
    }

    
    res = f_write(&file, "hello", strlen("hello"), (UINT *)&len);
    if(res != FR_OK)
    {
        printf("f_write error!\r\n");
    }
    else
    {
        printf("write %d byte to file\r\n", len);
    }
    f_close(&file);
#endif    
    
    
    while(1)
    {
        printf("run demo task\r\n");
#if 0
        res = f_mount(&fs, "", 1);
        if(res != FR_OK)
        {
            printf("f_mount error");
            sleep(10);
            continue;
        }
#endif
        
        res = f_open(&file, "hello.txt", FA_OPEN_EXISTING | FA_READ);
        if(res != FR_OK)
        {
            printf("f_open error\r\n");
            sleep(10);
            continue;
        }
        
        res = f_read(&file, buf, sizeof(buf), (UINT *)&len);
        if(res != FR_OK)
        {
            printf("f_read error!\r\n");
        }
        else
        {
            buf[len] = 0;
            printf("read from file: %s\r\n", buf);
        }
        
        res = f_close(&file);
        if(res != FR_OK)
        {
            printf("f_close error!\r\n");
        }
        sleep(10);
    }

#else
    while(1)
    {
        printf("run demo task\r\n");
        sleep(1);
    }
#endif

}